<?php
/**
 * $pager =  new cls_pager($total,$pernum);
 * $limit = $pager->getlimit();//获得limit 语句
 * $pagerhtml = $pager->gethtml();//获得分页效果
 *
 */
class pager 
{
    private $total;//总条数
    private $pagetotal;//总页数
    private $curpage;//当前页
    private $pagenum;//每页数
    private $limit;//limit 语句
    private $nextpage;
    private $prepage;
    private $url='';
    public function pager($total,$pernum=20)
    {
        $this->total = $total;
        $this->pagenum = $pernum;
        $this->pagetotal = ($total>0)? ceil($this->total / $this->pagenum): 1;
        $this->curpage = (isset($_GET['p']) && ($_GET['p'] > 0)) ? intval($_GET['p']) : 1;
        $this->curpage = ($this->curpage > $this->pagetotal) ? $this->pagetotal : $this->curpage;
        $this->nextpage = ($this->curpage == $this->pagetotal) ? '' : ($this->curpage + 1);
        $this->prepage = ($this->curpage == 1) ? '' : ($this->curpage - 1);
    }
    public function getlimit()
    {	
        $start = ($this->curpage - 1) * $this->pagenum;
        $str = " limit $start,$this->pagenum";
        return $str;
    }
    /**
     * 计算limit值
     */
    public function get_limit()
    {
        $start = ($this->curpage - 1) * $this->pagenum;
        return " $start,$this->pagenum";
    }
    
    public function geturl()
    {
    	if($this->url==''){
    		$this->url = $_SERVER['REQUEST_URI'];
    	}
    	$this->url = preg_replace('/[?,&]p=(\w)+/','',$this->url);
        $this->url .= (strpos($this->url,"?") === false) ? '?' : '&'; 
        return $this->url;
    }
    public function seturl($url){
    	$this->url=$url;
    }
    public function gethtml()
    {
        $s = $this->curpage - 5;
        $i = ($s > 0) ? $s : 1;
        $e = $this->curpage + 5;
        $end = ($e < $this->pagetotal) ? $e : $this->pagetotal;
        $html = '';
        $url = $this->geturl();

        if($this->curpage > 5) {
            $html .= "<a href=".$url."p=1>首页</a>&nbsp;";
        }
        if($this->prepage) {
            $html .= "<a href=".$url."p=".$this->prepage.">上一页</a>&nbsp;";
        }
		
		if($end && $end != 1)
		{
	        for($i;$i <= $end; $i++) {
	            if($i == $this->curpage) {
	                $html .= $i;
	            } else {
	                $html .= "<a href=".$url."p=$i>$i</a>&nbsp;";
	            }
	        }
	    }

        if($this->nextpage && ($this->nextpage <= $this->pagetotal)) {
            $html .= "<a href=".$url."p=".$this->nextpage.">下一页</a>&nbsp;";
        }

        if(($this->curpage + 5) < $this->pagetotal) {
            $html .= "<a href=".$url."p=".$this->pagetotal.">末页</a>&nbsp;";
        }

        $html .= "  共 $this->total 个 总共有$this->pagetotal 页 当前为第 $this->curpage 页";
        return $html;
    }
}